
<template>
<div class="body">
  <div class="container right-panel-active">
    <!-- Sign Up -->
    <div class="container__form container--signup">
      <form class="form" id="form1">
        <h2 class="form__title">Login</h2>
          <el-input placeholder="手机号/邮箱" v-model="phonemail" clearable></el-input>
          <br>
          <el-input placeholder="请输入密码" v-model="pwd" show-password></el-input>
        <button class="btn" @click="login">登录</button>
      </form>
    </div>

    <!-- Sign In -->
    <div class="container__form container--signin">
      <form  class="form" id="form2">
        <h2 class="form__title">register</h2>
          <el-input placeholder="请输入用户名" v-model="uname" clearable @blur="change_uname"></el-input>
          <br>
          <el-input placeholder="手机号/邮箱" v-model="input01" clearable @blur="change_uname02"></el-input>
          <br>
          <el-input placeholder="请输入密码" v-model="input02" show-password ></el-input>
          <br>
          <el-input placeholder="再次输入密码" v-model="input03" show-password ></el-input>
          <br>
          <div class="s-canvas" >
            <el-link style="position: relative;top: -15px" @click="createdCode('s-canvas')">获取验证码</el-link>
            <canvas  id="s-canvas"  :width="contentWidth" :height="contentHeight"></canvas>
            <el-input placeholder="请输入验证码" v-model="validation" ></el-input>
          </div>
        <button class="btn" @click="add">注册</button>
      </form>
    </div>

    <!-- Overlay -->
    <div class="container__overlay">
      <div class="overlay">
        <div class="overlay__panel overlay--left">
          <button class="btn" id="signIn">去注册</button>
        </div>
        <div class="overlay__panel overlay--right">
          <button class="btn" id="signUp">去登录</button>
        </div>
      </div>
    </div>
  </div>
</div>
</template>

<script>
  //导入css样式
  require("./css/css4.css")
  require("./css/css5.css")

  setTimeout(function () {
    require("./script02.js");
  },100)

  //定义全局的正则表达式方便其他方法使用
  let eli = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/

  let phone = /^1[3|4|5|7|8][0-9]{9}$/

  let pwd02= /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/

    export default {
        name: "Login",
      props: {
        fontSizeMin: {
          type: Number,
          default: 25
        },
        fontSizeMax: {
          type: Number,
          default: 30
        },
        backgroundColorMin: {
          type: Number,
          default: 255
        },
        backgroundColorMax: {
          type: Number,
          default: 255
        },
        colorMin: {
          type: Number,
          default: 0
        },
        colorMax: {
          type: Number,
          default: 160
        },
        lineColorMin: {
          type: Number,
          default: 100
        },
        lineColorMax: {
          type: Number,
          default: 255
        },
        dotColorMin: {
          type: Number,
          default: 0
        },
        dotColorMax: {
          type: Number,
          default: 255
        },
        contentWidth: {
          type: Number,
          default: 120
        },
        contentHeight: {
          type: Number,
          default: 34
        }
      },
        data(){
            return{
                uname:"",
                input01: '',
                input02: '',
                input03: '',
                pwd:'',
                phonemail:'',
              validation:""
            }
        },
        methods:{
          //------------注册-------------//

          //判断用户名否重复
          change_uname(){

            let uname = this.uname

            let users = new URLSearchParams();


            if (uname!=undefined && uname!=""){
              users.append("uName",uname)
            }

            this.$axios.post("queryRepetition.action",users).
            then(request=>{
              console.log(request.data.msg)
              if (request.data.msg=='找到了'){
                this.uname = ""
                this.warning()
              }
            }).
            catch()

          },
          //判断邮箱||手机号是否重复
          change_uname02(){

            let account = this.input01;

            let users = new URLSearchParams();


            if (eli.test(account) || phone.test(account)) {
              if (!eli.test(account)) {
                //手机号
                users.append("phone", account)
              }
              if (!phone.test(account)) {
                //邮箱
                users.append("mailAddress", account)
              }
            }

            this.$axios.post("queryRepetition02.action",users).
            then(request=>{
              if (request.data.msg=='找到了'){
                this.input01 = ""
                this.warning02()
              }
            }).
            catch()

          },
          //添加用户
          add(){
                let account=this.input01

                let pwd01 = this.input02

                let pwd03 = this.input03

                let uname = this.uname

                let users = new URLSearchParams();

            if (uname!=undefined && uname!=""){
                //判断邮箱或手机号是否输入正确
                if (eli.test(account) || phone.test(account)){
                  if(!eli.test(account)){
                    //手机号
                    users.append("phone",account)
                  }
                  if(!phone.test(account)){
                    //邮箱
                    users.append("mailAddress",account)
                  }
                  //成功后判断密码
                  if (pwd02.test(pwd01)){

                    //判断两次密码是否重复
                    if (pwd01==pwd03){

                      users.append('uName',uname)
                      users.append('uPwd',pwd01)
                      users.append('accountState',0)
                      users.append("balance",0.0)

                       if (this.identifyCode == this.validation){
                         //异步添加
                         this.$axios.post("register.action",users).
                         then(request=>{
                           if (request.data.msg=='成功'){
                             //成功后调用的方法
                             this.success()
                           }
                         }).
                         catch()
                       }else {
                         this.$message.error("验证码输入有误!!")
                       }

                    }else {
                      //失败后调用提示框方法
                      this.error03()
                    }

                  }else {
                    //失败后调用提示框方法
                    this.error02()
                  }
                }else {
                  //失败后调用提示框方法
                  this.error01()
                }

            }else {
              //失败后调用提示框方法
              this.error04()
            }


            },
          //成功后调用的方法
          success() {
              this.input01 = ""

              this.input02 = ""

              this.input03 = ""

              this.uname = ""

              this.validation=""

                this.$message({
                    message: '注册成功',
                    type: 'success'
                });
            },
          //失败后调用提示框方法
          error01() {
                this.$message.error('邮箱或手机号输入错误!');
            },
          //失败后调用提示框方法
          error02() {
                this.$message.error('密码输入错误,长度至少为8，至少含有一个字母和一个数字!');
            },
          //失败后调用提示框方法
          error03(){
                this.$message.error('两次密码必须一致!');
            },
          //失败后调用提示框方法
          error04() {
            this.$message.error('用户名不能为空！');
            },
          //失败后调用提示框方法
          warning() {
            this.$message({
              message: '该用户名已被使用！',
              type: 'warning'
            });

          },
          //失败后调用提示框方法
          warning02() {
            this.$message({
              message: '该邮箱或手机号已被使用！',
              type: 'warning'
            });

          },

          //------------登录-------------//

          login(){

           let phonemail = this.phonemail

           let pwd = this.pwd

           let users = new URLSearchParams()

              //判断邮箱或手机号是否输入正确
              if (eli.test(phonemail) || phone.test(phonemail)){
                if(!eli.test(phonemail)){
                  //手机号
                  users.append("phone",phonemail)
                }
                if(!phone.test(phonemail)){
                  //邮箱
                  users.append("mailAddress",phonemail)
                }
                //成功后判断密码
                if (pwd02.test(pwd)){

                  users.append("uPwd",pwd)

                    //异步添加
                    this.$axios.post("login.action",users).
                    then(request=>{
                      if (request.data!=null && request.data!=""){
                        //成功后调用的方法
                        this.open3()
                        //存入sessionStorage
                        sessionStorage.setItem("id",request.data.id);
                        sessionStorage.setItem("uName",request.data.uname);
                        sessionStorage.setItem("uPwd",request.data.upwd);
                        sessionStorage.setItem("phone",request.data.phone);
                        sessionStorage.setItem("mailAddress",request.data.mailAddress);
                        sessionStorage.setItem("receivingAddressId",request.data.receivingAddressId);
                        sessionStorage.setItem("commercialState",request.data.commercialState);
                        sessionStorage.setItem("supplierState",request.data.supplierState);
                        //跳转路由
                        this.$router.push("/");
                      }else {
                        this.$message.error("登陆失败账号冻结或密码错误！！")
                        return""
                      }
                    }).
                    catch()

                }else {
                  //失败后调用提示框方法
                  this.error02()
                }
              }else {
                //失败后调用提示框方法
               this.$message.error("邮箱或手机号输入错误！！")
              }



          },
          open3() {
            this.phonemail = ""

            this.pwd = ""

            this.$notify({
              title: '登陆成功',
              message: '成功',
              position: 'bottom-left',
              type: 'success'
            });
          },
          //成功后调用的方法
          success02() {

            this.phonemail = ""

            this.pwd = ""

            this.$message({
              message: '登录成功',
              type: 'success'
            });
          },
          //-------验证码--------//

          // 生成4个随机数
          createdCode(id) {
            const len = 4
            const codeList = []
            const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz0123456789'
            const charsLen = chars.length
            for (let i = 0; i < len; i++) {
              codeList.push(chars.charAt(Math.floor(Math.random() * charsLen)))
            }
            this.identifyCode = codeList.join('')
            this.$emit('getIdentifyCode', this.identifyCode.toLowerCase())
            this.drawPic(id)
          },

          // 生成一个随机数
          randomNum(min, max) {
            return Math.floor(Math.random() * (max - min) + min)
          },
          // 生成一个随机的颜色
          randomColor(min, max) {
            const r = this.randomNum(min, max)
            const g = this.randomNum(min, max)
            const b = this.randomNum(min, max)
            return 'rgb(' + r + ',' + g + ',' + b + ')'
          },

          drawPic(id) {
            const canvas = document.getElementById(id)
            console.log(canvas)
            const ctx = canvas.getContext('2d')
            ctx.textBaseline = 'bottom'
            // 绘制背景
            ctx.fillStyle = this.randomColor(this.backgroundColorMin, this.backgroundColorMax)
            ctx.fillRect(0, 0, this.contentWidth, this.contentHeight)
            // 绘制文字
            for (let i = 0; i < this.identifyCode.length; i++) {
              this.drawText(ctx, this.identifyCode[i], i)
            }
            this.drawLine(ctx)
            this.drawDot(ctx)
          },

          drawText(ctx, txt, i) {
            ctx.fillStyle = this.randomColor(this.colorMin, this.colorMax)
            ctx.font = this.randomNum(this.fontSizeMin, this.fontSizeMax) + 'px SimHei'
            const x = (i + 1) * (this.contentWidth / (this.identifyCode.length + 1))
            const y = this.randomNum(this.fontSizeMax, this.contentHeight - 5)
            var deg = this.randomNum(-45, 45)
            // 修改坐标原点和旋转角度
            ctx.translate(x, y)
            ctx.rotate(deg * Math.PI / 180)
            ctx.fillText(txt, 0, 0)
            // 恢复坐标原点和旋转角度
            ctx.rotate(-deg * Math.PI / 180)
            ctx.translate(-x, -y)
          },

          // 绘制干扰线
          drawLine(ctx) {
            for (let i = 0; i < 5; i++) {
              ctx.strokeStyle = this.randomColor(this.lineColorMin, this.lineColorMax)
              ctx.beginPath()
              ctx.moveTo(this.randomNum(0, this.contentWidth), this.randomNum(0, this.contentHeight))
              ctx.lineTo(this.randomNum(0, this.contentWidth), this.randomNum(0, this.contentHeight))
              ctx.stroke()
            }
          },

          // 绘制干扰点
          drawDot(ctx) {
            for (let i = 0; i < 80; i++) {
              ctx.fillStyle = this.randomColor(0, 255)
              ctx.beginPath()
              ctx.arc(this.randomNum(0, this.contentWidth), this.randomNum(0, this.contentHeight), 1, 0, 2 * Math.PI)
              ctx.fill()
            }
          },

        }
    }

</script>

<style scoped>

</style>
